import React, { useState } from 'react';
import {
  Form,
  Row,
  Col,
  Button,
  DatePicker,
  Select,
  Table,
  Input,
  message,
} from 'antd';
import moment from 'moment';
import { history } from 'umi';
import request from '@/http';
import { any } from 'prop-types';
const { RangePicker } = DatePicker;
const { Option } = Select;

export default () => {
  const [expand, setExpand] = useState(true);
  const [form] = Form.useForm();
  const formItemLayout = {
    labelCol: {
      xs: { span: 7 },
      sm: { span: 4 },
    },
    wrapperCol: {
      xs: { span: 24 },
      sm: { span: 16 },
    },
  };
  const [select2, setSelect2] = useState([]);
  const loadSelect2 = async () => {
    const result: any = await request.post(
      '/api/common_module/a_t_s/getCourse',
    );
    if (result.success) {
      setSelect2(result.data);
    }
  };
  React.useEffect(() => {
    loadSelect2();
  }, []);
  const getFields = () => {
    const count = expand ? 10 : 6;
    const children = [];
    children.push(
      <Col span={8}>
        <Form.Item name="date" label="日期:">
          <RangePicker
            style={{
              width: '100%',
            }}
            ranges={{
              Today: [moment(), moment()],
              'This Month': [
                moment().startOf('month'),
                moment().endOf('month'),
              ],
            }}
          />
        </Form.Item>
      </Col>,

      <Col span={8}>
        <Form.Item name="courseName" label="项目名称">
          <Select
            placeholder="请选择..."
            optionFilterProp="children"
            filterOption={(input, option: any) =>
              option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
            filterSort={(optionA, optionB) =>
              optionA.children
                .toLowerCase()
                .localeCompare(optionB.children.toLowerCase())
            }
          >
            {select2.map((item: any) => {
              return <Option value={item.courseName}>{item.courseName}</Option>;
            })}
          </Select>
        </Form.Item>
      </Col>,

      <Col span={8}>
        <Form.Item name="考勤情况" label="考勤情况">
          <Select
            placeholder="请选择..."
            optionFilterProp="children"
            filterOption={(input, option: any) =>
              option.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
            }
            filterSort={(optionA, optionB) =>
              optionA.children
                .toLowerCase()
                .localeCompare(optionB.children.toLowerCase())
            }
          >
            <Option value="1">正常</Option>
            <Option value="2">迟到</Option>
            <Option value="3">早退</Option>
            <Option value="4">缺勤</Option>
            <Option value="5">请假</Option>
          </Select>
        </Form.Item>
      </Col>,
    );
    return children;
  };

  const columns = [
    {
      title: '日期',
      dataIndex: 'projectDate',
      key: 'projectDate',
    },
    {
      title: '学号',
      dataIndex: 'userNo',
      key: 'userNo',
    },
    {
      title: '姓名',
      dataIndex: 'studentName',
      key: 'studentName',
    },
    {
      title: '项目名称',
      dataIndex: 'courseName',
      key: 'courseName',
    },
    {
      title: '实训老师',
      dataIndex: 'trainTeacher',
      key: 'trainTeacher',
    },
    {
      title: '责任老师',
      dataIndex: 'dutyTeacher',
      key: 'dutyTeacher',
    },
    {
      title: '考勤情况',
      dataIndex: 'attendanceType',
      key: 'attendanceType',
    },
    {
      title: '应签到',
      dataIndex: 'signInTime',
      key: 'signInTime',
    },
    {
      title: '实签到',
      dataIndex: 'realStartTime',
      key: 'realStartTime',
    },
    {
      title: '应签退',
      dataIndex: 'signOutTime',
      key: 'Sign',
    },
    {
      title: '实签退',
      dataIndex: 'realEndTime',
      key: 'realEndTime',
    },
    {
      title: '操作',
      key: 'action',
      render: (text: any) => {
        console.log(text);
        if (text.attendance == '正常') {
          return <a></a>;
        } else if (text.attendance == '请假') {
          return (
            <Button
              type="link"
              onClick={() => {
                history.push('/global/askForLeave/particulars');
              }}
            >
              查看请假原因
            </Button>
          );
        } else {
          return (
            <Button
              type="link"
              onClick={() => {
                history.push('/global/askForLeave/dispose');
              }}
            >
              请假申请
            </Button>
          );
        }
      },
    },
  ];

  const [dataSource, setDataSource] = useState([]);
  const loadAttend = async (queryParams: any) => {
    try {
      setExpand(true);
      const result: any = await request.get(
        '/api/student/attendance/getAttendance',
        {
          params: {
            ...queryParams,
          },
        },
      );
      if (result.success) {
        let sum = 0;
        const data = result.data.records.map((user: any) => ({
          key: `attendance_${sum++}`,
          leaveId: user.leaveId,
          projectDate: user.projectDate,
          teamName: user.teamName,
          collegesName: user.collegesName,
          majorName: user.majorName,
          gradeName: user.gradeName,
          className: user.className,
          courseName: user.courseName,
          dutyTeacher: user.dutyTeacher,
          trainTeacher: user.trainTeacher,
          userNo: user.userNo,
          studentName: user.studentName,
          signInTime: user.signInTime,
          signOutTime: user.signOutTime,
          realStartTime: user.realStartTime == null ? '/' : user.realStartTime,
          realEndTime: user.realEndTime == null ? '/' : user.realEndTime,
          attendanceType:
            user.attendanceType == '1'
              ? '正常'
              : user.attendanceType == '2'
              ? '迟到'
              : user.attendanceType == '3'
              ? '早退'
              : user.attendanceType == '4'
              ? '缺勤'
              : '请假',
        }));
        setExpand(false);
        setDataSource(data);
      }
    } catch (e) {
      message.error(e.message);
    }
  };

  React.useEffect(() => {
    loadAttend('');
  }, []);

  const onFinish = (values: any) => {
    const data = {
      startDate: values.date ? values.date[0].format('yyyy-MM-DD') : '',
      endDate: values.date ? values.date[1].format('yyyy-MM-DD') : '',
      courseName: values.courseName,
    };
    loadAttend(data).finally();
    console.log(data);
  };

  return (
    <>
      <Form
        {...formItemLayout}
        form={form}
        name="advanced_search"
        className="ant-advanced-search-form"
        onFinish={onFinish}
      >
        <Row gutter={24}>{getFields()}</Row>
        <Row>
          <Col span={24} style={{ textAlign: 'left' }}>
            <Button type="primary" style={{ width: '7%' }} htmlType="submit">
              查询
            </Button>
            <Button
              style={{ margin: '0 8px', width: '7%' }}
              onClick={() => {
                form.resetFields();
              }}
            >
              重置
            </Button>
          </Col>
        </Row>
      </Form>
      <Table columns={columns} loading={expand} dataSource={dataSource} />
    </>
  );
};
